
package com.hlkj.pay.listener;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.ad.IAdPayOrderAppService;
import com.hlkj.pay.common.constants.BaseConstants;
import com.hlkj.pay.common.constants.MqConstant;
import com.hlkj.pay.dto.common.OrderStatusDto;
import com.hlkj.pay.service.common.IBusinessLogService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2024/10/24 12:58
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "rocketmq", name = "enabled", havingValue = "true")
@RocketMQMessageListener(topic = MqConstant.AD_ORDER_STATUS_RECORD_TOPIC, consumerGroup = MqConstant.AD_ORDER_STATUS_RECORD_TOPIC)
public class AdOrderStatusConsumer implements RocketMQListener<OrderStatusDto>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private IAdPayOrderAppService adPayOrderAppService;

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private IBusinessLogService businessLogService;

    @Value("${server.port}")
    private String serverPort;

    @Override
    @Async("adOrderStatusTaskExecutor")
    public void onMessage(OrderStatusDto orderStatusDto) {
        if (orderStatusDto.getDelaySendTime() != null) {
            LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(orderStatusDto.getDelaySendTime()), ZoneId.of(BaseConstants.shanghaiTimeZoneId));
            log.info("ad订单状态变更 mq:{},sendTime:{},now:{}", JsonUtils.toJsonString(orderStatusDto), dateTime.format(formatter),
                    ZonedDateTime.now(ZoneId.of(BaseConstants.shanghaiTimeZoneId)).toLocalDateTime().format(formatter));
        }
        // businessLogService.consumeOrderStatusLog(MqConstant.ORDER_STATUS_RECORD_TOPIC, orderStatusDto);
        adPayOrderAppService.processOrderStatusMessage(orderStatusDto);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        // 设置当前实例的名称
        consumer.setInstanceName(MqConstant.AD_ORDER_STATUS_RECORD_TOPIC + "_" + serverPort);
    }

}
